//
//  NSDate+Extensions.m
//  CDatePicker
//
//  Created by Mac on 2023/12/8.
//

#import "NSDate+Extensions.h"

@implementation NSDate (Extensions)


- (NSInteger)currentYear {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear fromDate:self];
    return components.year;
}

- (NSInteger)currentMonth {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSCalendarUnitMonth fromDate:self];
    return components.month;
}

- (NSInteger)currentDay {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSCalendarUnitDay fromDate:self];
    return components.day;
}

+ (NSInteger)numberOfMonthsInYear:(NSInteger)year {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *startComponents = [[NSDateComponents alloc] init];
    startComponents.year = year;
    startComponents.month = 1;
    startComponents.day = 1;
    
    NSDate *startDate = [calendar dateFromComponents:startComponents];
    
    NSDateComponents *endComponents = [[NSDateComponents alloc] init];
    endComponents.year = year;
    endComponents.month = 12;
    endComponents.day = 31;
    
    NSDate *endDate = [calendar dateFromComponents:endComponents];
    
    NSRange range = [calendar rangeOfUnit:NSCalendarUnitMonth inUnit:NSCalendarUnitYear forDate:startDate];
    return range.length;
}

+ (NSInteger)numberOfDaysInMonth:(NSInteger)month year:(NSInteger)year {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [[NSDateComponents alloc] init];
    components.year = year;
    components.month = month;
    components.day = 1;
    
    NSDate *firstDayOfMonth = [calendar dateFromComponents:components];
    
    NSRange range = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:firstDayOfMonth];
    return range.length;
}


+ (NSInteger)dayOfWeekForYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    NSDateComponents *components = [[NSDateComponents alloc] init];
    components.year = year;
    components.month = month;
    components.day = day;
    
    NSDate *date = [calendar dateFromComponents:components];
    
    NSCalendarUnit dayOfWeekUnit = NSCalendarUnitWeekday;
    NSDateComponents *weekdayComponent = [calendar components:dayOfWeekUnit fromDate:date];
    
    return weekdayComponent.weekday;
}



+ (NSDate *)addHours:(NSInteger)hours toDate:(NSDate *)originalDate {
    // 计算小时对应的时间间隔
    NSTimeInterval interval = hours * 60 * 60;

    // 使用dateByAddingTimeInterval方法获取新的NSDate对象
    NSDate *newDate = [originalDate dateByAddingTimeInterval:interval];

    return newDate;
}


@end
